package com.example.cloud.service.impl;

import com.example.cloud.util.PageRequest;
import com.example.cloud.util.PageResult;
import com.example.cloud.entity.User;
import com.example.cloud.mapper.UserMapper;
import com.example.cloud.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 用户服务实现类
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    
    private final UserMapper userMapper;
    
    @Override
    public User findById(Long id) {
        return userMapper.findById(id);
    }
    
    @Override
    public PageResult<User> getUserList(User user, PageRequest pageRequest) {
        // 查询总数
        int total = userMapper.count(user);
        
        // 分页查询
        List<User> list = userMapper.findByPage(user, pageRequest);
        
        // 返回分页结果
        return new PageResult<>(total, list);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public User save(User user) {
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);
        userMapper.insert(user);
        return user;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public User update(User user) {
        user.setUpdateTime(new Date());
        userMapper.update(user);
        return user;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long id) {
        userMapper.deleteById(id);
    }
    
    @Override
    public Long getUserCount(User user) {
        return Long.valueOf(userMapper.count(user));
    }

    @Override
    public User findByOpenid(String openid) {
        return userMapper.findByOpenid(openid);
    }
} 